package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Models.TankBrews;
import Models.TankSchedule;

public class TankSchedulePresenter extends AbstractPresenter<TankSchedule> {
	final String SINGLEITEM = "tankSchedule";
	final String MULTIITEM = "tankSchedules";
	
	public TankSchedule getEmptyEntity(){
		TankSchedule entity = new TankSchedule();
		return entity;
	}
	
	public ArrayList<TankSchedule> tryJSONParseArray(String input){
		return super.doJSONParseArray(input, SINGLEITEM, MULTIITEM);
	}
	
	public TankSchedule tryJSONParse(String input){
		return super.doJSONParse(input, SINGLEITEM);
	}
	
	public TankSchedule createItemFromJSONObject(JSONObject jsonObject){
		TankSchedule item = new TankSchedule();
		try{
			item.setIndex(jsonObject.getInt("index"));
			item.setSecondaryTank(jsonObject.getBoolean("secondaryTank"));
			item.setTankDesg(jsonObject.getString("tankDesg"));
			item.setTankID(jsonObject.getInt("tankID"));
			
			//Set LabType Collection
			ArrayList<TankBrews> brews = new ArrayList<TankBrews>();
			if(!jsonObject.isNull("brews")){
				Object itm = jsonObject.get("brews");
				TankBrewsPresenter presenter = new TankBrewsPresenter();
				if(itm instanceof JSONArray){
					JSONArray jPSTArray = (JSONArray)itm;
					for(int i=0; i<jPSTArray.length(); i++){
						JSONObject jsonItem = jPSTArray.getJSONObject(i);
						brews.add(presenter.createItemFromJSONObject(jsonItem));
					}
				} else {
					JSONObject jsonItem = (JSONObject)itm;
					brews.add(presenter.createItemFromJSONObject(jsonItem));
				}
				item.setBrews(brews);
			}
			
			return item;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(TankSchedule item){
		try{
			JSONObject json = new JSONObject();
			json.put("index", item.getIndex());
			json.put("secondaryTank", item.isSecondaryTank());
			json.put("tankDesg", item.getTankDesg());
			json.put("tankID", item.getTankID());
			
			//Create Beers Collection
			if(item.getBrews()!=null){
				TankBrewsPresenter presenter = new TankBrewsPresenter();
				if(item.getBrews().size()>0){
					JSONArray jsonArray = new JSONArray();
					for(int i=0; i<item.getBrews().size(); i++){
						jsonArray.put(presenter.createJSON(item.getBrews().get(i)));
					}
					json.put("brews", jsonArray);
				}
			}
			
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
